<script setup lang="ts">
import { useEmptyObject, useOmit } from 'co-utils-vue';
import { ElMessage, FormInstance, FormRules } from 'element-plus';
import { ComputedRef } from 'vue';

import { updateUserInfo } from '@/api/user';
import { User } from '@/api/user/type';

const router = useRouter();
const userInfo = inject<ComputedRef<User.IUserInfoResponse>>('USER-INFO');
const formRulesRef = ref<FormInstance>();
interface IForm {
  password: string;
  confirmPassword:string;
  oldPassword: string;
}
const formModel = ref<IForm>({
  password: '',
  confirmPassword: '',
  oldPassword: ''
});
const formRules = reactive<FormRules<IForm>>({
  password: [
    {
      required: true,
      message: '密码不为空'
    },
    {
      required: true,
      min: 6,
      max: 16,
      message: '密码长度6-16位'
    }
  ],
  confirmPassword: [
    {
      required: true,
      message: '密码不为空'
    },
    {
      required: true,
      min: 6,
      max: 16,
      message: '密码长度6-16位'
    },
    {
      required: true,
      min: 6,
      max: 8,
      validator: (rule, value, callback) => {
        if (value !== formModel.value.password) {
          callback(new Error('两次密码不一致'));
        }
        callback();
      },
      message: '两次密码不一致'
    }
  ]
});
const handleSubmit = async () => {
  await formRulesRef.value?.validate();
  const _data = useOmit(formModel.value, ['confirmPassword']);
  await updateUserInfo({
    ..._data,
    oldPassword: _data.oldPassword,
    id: userInfo!.value!.id });
  formModel.value = useEmptyObject(formModel.value);
  ElMessage.warning({
    message: '密码已更改，请重新登录！',
    duration: 1500
  });
  setTimeout(() => {
    router.replace({
      name: 'Login'
    });
  }, 1500);
};
</script>

<template>
  <div class="cz-p-2">
    <el-form
      ref="formRulesRef"
      label-position="right"
      label-width="80px"
      :model="formModel"
      :rules="formRules"
    >
      <el-form-item
        label="原密码"
        prop="oldPassword"
      >
        <el-input
          v-model.trim="formModel.oldPassword"
          type="password"
          prefix-icon="Lock"
          placeholder="原密码"
        />
      </el-form-item>
      <el-form-item
        label="新密码"
        prop="password"
      >
        <el-input
          v-model.trim="formModel.password"
          prefix-icon="Lock"
          type="password"
          placeholder="新密码"
        />
      </el-form-item>
      <el-form-item
        label="确认密码"
        prop="confirmPassword"
      >
        <el-input
          v-model.trim="formModel.confirmPassword"
          prefix-icon="Lock"
          type="password"
          placeholder="确认密码"
        />
      </el-form-item>
    </el-form>
    <div class="cz-flex cz-justify-center">
      <el-button
        type="primary"
        icon="Check"
        @click="handleSubmit"
      >
        提交
      </el-button>
    </div>
  </div>
</template>

<style scoped lang="scss">

</style>
